package db

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/godror/godror"
	log "github.com/sirupsen/logrus"
)

// 数据库类型
type DbType string

const (
	//mysql
	MYSQL DbType = "mysql"
	//oracle
	ORACLE DbType = "godror"
)

// 字符串转DbType
func ToDbType(s string) DbType {
	switch s {
	case "mysql":
		return MYSQL
	case "godror", "oracle":
		return ORACLE
	default:
		return ""
	}
}

type ConnectLogo struct {
	//数据库类型
	Type   DbType `json:"type"`
	User   string `json:"user"`
	Passwd string `json:"passwd"`
	Host   string `json:"host"`
	Port   int    `json:"port"`
	DbName string `json:"dbName"`
	Params string `json:"params"`
}

// 打印
func (c ConnectLogo) String() string {
	return fmt.Sprintf("type:%s,user:%s,passwd:%s,host:%s,port:%d,dbName:%s,params:%s", c.Type, c.User, c.Passwd, c.Host, c.Port, c.DbName, c.Params)
}

// 数据库连接
func GetDb(c ConnectLogo) *sql.DB {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s", c.User, c.Passwd, c.Host, c.Port, c.DbName, c.Params)
	//连接数据库
	db, err := sql.Open(string(c.Type), dsn)
	if err != nil {
		log.Error("连接数据库失败", err)
		return nil
	}
	//测试
	err = db.Ping()
	if err != nil {
		log.Error("连接数据库失败", err)
		return nil
	}
	return db
}
